<?php
    
    // models
    use_model('file_folders','file_types');

    class Files extends ActiveRecord {
        
        var $allowed_types      = array();
        var $disallowed_types   = array();
        // if you are using this class to deal with files that 
        // have been added to the system without uploading them, 
        // set this to false. by default this class looks for $_FILES
        var $is_file_upload     = true; 
        
        var $file_filters = array(
                                 'all' => 'all',
                                 'image' => 'image',
                                 'application' => 'application',
                                 'text' => 'text'
                                 );
        
        function Files()
        {
            $conf = array('table'=>DB_PREFIX.'files');
            $this->ActiveRecord($conf);  
            
            $max_upload = trim( ini_get('upload_max_filesize') );
            
            $delimiter = strtolower( substr($max_upload, -1 , 1) );
            switch ( $delimiter )
            {
                case 'g':
                    $max_upload *= 1024;
                case 'm':
                    $max_upload *= 1024;
                case 'k':
                   $max_upload *= 1024;
            }
            
            define('MAX_FILE_SIZE', $max_upload); // this is ~
                      
        }
            
        function validate()
        {
            $this->is_valid_file();
        }
        
        function before_validation_on_create()
        {
            $this->add_file();
        }
        
        // match mime and file extention
        function is_valid_file()
        {
            $this->get_file_types();
            $is_valid = false;
            foreach( $this->allowed_types as $type )
            {                
                $ext = strtolower(substr($this->fields['name'], strrpos($this->fields['name'], '.') + 1));
                if ( strcasecmp($this->fields['type'], $type['mime']) == 0 
                     &&  strcasecmp($ext,$type['ext']) == 0 )
                {
                    $is_valid = true;
                    break;
                }
            }
            if ( !$is_valid )
            {
                $this->add_error('File', 'File type not allowed on server.');
            }
            return $is_valid;
        }
        
        function get_file_types()
        {
            $file_types = new File_Types();
            $this->allowed_types = $file_types->get_allowed_types();
        }
        
        function add_file()
        {
            if ( !$this->is_file_upload )
            {
                return;
            }
            use_pixel_lib('class.upload.php');
            $file =& Upload::getFile('name');
            if (!$file) {                
                $this->add_error('File','Failed to transfer file.');
                return;
            }
            // check file size first
            if ( $file->checkSize(MAX_FILE_SIZE) )
            {
                // safe name the file
                $file->nameToSafe();
                
                $this->set('name', $file->name) ;
                $this->set('type', $file->type) ;
                $this->set('ext',  $file->ext) ;
                $this->set('size', $file->size) ;
                $this->set('created',DB_DATESTAMP);
                $this->set('last_modified',DB_DATESTAMP);
                // check that file name is valid
                if(!$this->is_valid_file()) 
                {
                    $this->unload();
                    return false;
                }
                
                $folders     =& new File_Folders();
                $upload_path = $folders->get_server_path($this->get('file_folder_id'));
                if ( !$file->moveTo($upload_path,false) ) // don't overwrite a file that already exists
                {                    
                    $this->add_error('File','Upload failed: '.$file->getError());
                }
            } else {
                $this->add_error('File','Your file exceeds the max of: '.string_format_file_size(MAX_FILE_SIZE));
            }
        }        
        
        function delete_file($id)
        {
            $this->load($id);
            if($this->is_loaded()){
                $folders = new File_Folders();
                $path = $folders->get_server_path($this->get('file_folder_id'));
                $filepath = $path.'/'.$this->get('name');
                if(file_exists($filepath)){
                    @unlink($filepath);                
                    if($this->delete()) $this->unload();
                    return true;
                } else { // file doesnt really exist, so kill from db anyways                
                    if($this->delete()) $this->unload();
                    return true;
                }
            } else {
                trigger_error('Can not delete file, no id loaded.',WARNING);
            }      
            return false;
        }
        
        // should read teh files directory and make entries if possible
        // for files and folders
        function synch_from_server()
        {
            
        }
        
        function get_files_by_folder($id, $filter = 'all')
        {
            $where = '';
            if ( $filter != 'all' )
            {
                $where = " AND type LIKE '{$this->file_filters[$filter]}/%'";
            }
            return $this->find( array('conditions'=>array("file_folder_id=? $where",$id), 'order'=>'name' ));
        }
        
        function get_filters()
        {
            return $this->file_filters;
        }
        
    }

?>